package com.ddwl.gate.service;

import com.alibaba.fastjson.JSON;
import com.ddwl.common.constant.Constant;
import com.ddwl.common.exception.ParamException;
import com.ddwl.schema.bo.gate.kuaiDi100.QueryBo;
import com.ddwl.schema.vo.gate.kuaiDi100.QueryTrackVo;
import com.google.gson.Gson;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @Author hemiaojun
 * @Date 2021/10/12 11:19
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class KuaiDi100Service {

    private final RestTemplate restTemplate;

    @Value("${kuaidi100.customer}")
    private String customer;
    @Value("${kuaidi100.key}")
    private String key;


    public QueryTrackVo queryTrack(QueryBo bo) {
        String param = new Gson().toJson(bo);
        log.info("param : {}",param);
        String sign = DigestUtils.md5Hex(param+key+customer).toUpperCase();
        log.info("sign:{}",sign);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        // 设置请求参数
        MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("customer", customer);
        postParameters.add("sign", sign);
        postParameters.add("param", param);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(postParameters, headers);
        String result = restTemplate.postForObject(Constant.KUAI_DI_100_QUERY, httpEntity, String.class);

        ParamException.isNull(result,"快递查询出错");
        log.info("kuaidi100 query result:{}" , result);
        QueryTrackVo queryTrackVo = JSON.parseObject(result, QueryTrackVo.class);
        ParamException.isTrue(null != queryTrackVo.getResult() && !queryTrackVo.getResult(), queryTrackVo.getMessage());
        return queryTrackVo;
    }


}
